<template>
  <header style="height:74px">
    <div class="answer-header">
      <nav class="header-box-inner flex-center-wrap">
        <h1>
          <a :href="parseFullPath('/')" class="flex-center-wrap">
            <img
              alt="logo"
              class="web-logo"
              :src="
                [1, 2].includes(+headStyleType)
                  ? '//image.zlketang.com/public/news/images/new_official/other/black_logo.png'
                  : '//image.zlketang.com/public/news/images/new_official/other/white_logo.png'
              "
            />
          </a>
        </h1>
        <div class="header-interval-sign">·</div>
        <div class="answer-logo-box flex-center-wrap">
          <img
            src="//image.zlketang.com/public/news/images/new_official/answer_question/answer_center_logo.png"
            alt=""
            class="answer-logo"
          />
        </div>
        <div class="header-center flex-center-wrap">
          <div
            v-for="(item, index) in headerTabsNav"
            :key="index"
            class="header-tab-item"
            :class="currentNavTab === index + 1 ? 'header-tab-item-active' : ''"
            @click="chooseNavTab(index)"
          >
            <div>{{ item.name }}</div>
            <div
              v-if="index === 2 && +unReadCount > 0 && currentNavTab < 4"
              class="header-tab-item-count"
            >
              {{ unReadCount }}
            </div>
          </div>
        </div>
        <div class="header-right flex-center-wrap">
          <div @click="showSearchBox" class="search-box-new">
            <div class="search-input-new bs-border"></div>
            <i class="iconfont icon-sousuo1 search-icon flex-center"></i>
          </div>

          <!-- 学习记录和登录领课 -->
          <div class="flex-center-wrap">
            <template>
              <a
                v-if="isLogin"
                href="javascript:;"
                class="f14 head-study-btn"
                @click.stop="showStudy"
              >
                学习记录
              </a>
              <a
                v-else
                href="javascript:;"
                class="f14 head-study-btn head-study-btn-login"
                @click.stop="showStudy"
              >
                学习记录
              </a>
            </template>
            <div class="vertical-split-line"></div>
            <a
              :href="parseFullPath('/login.html')"
              v-show="!isLogin"
              class="get-course-btn  f14"
              @click.stop="aGoToLogin"
            >
              登录领课
            </a>
            <div class="flex-center" v-show="isLogin">
              <a
                target="_blank"
                :href="parseFullPath('/personal/index.html?name=1')"
                class="head-study-btn f14"
                @click="
                  handleZla(
                    '我的课程',
                    `我的课程${profession_name ? '_' + profession_name : ''}`
                  )
                "
              >
                我的课程
              </a>
              <img
                class="my-header"
                :src="parseResourceUrl(userData.headimgurl)"
                onerror="javascript:this.src='//image.zlketang.com/public/news/images/new_official/home/error-user-header.png'"
                alt="用户头像"
                @click.stop="
                  isShowStudy = false
                  isShowCourse = !isShowCourse
                "
              />
            </div>
          </div>
        </div>

        <!-- 学习记录弹窗 -->
        <div v-if="isShowStudy" class="study-dialog">
          <div style="padding: 0 20px">
            <slide-nav
              :navList="historyType"
              :currentType.sync="activeIndex"
              @selectedNav="handleHistory"
              active-bg="#F7F7F7"
              customBoxClass="flex-center-wrap flex-justify-between"
              customItemClass="study-slide-nav"
              customItemActiveClass="study-slide-nav"
            ></slide-nav>
          </div>
          <div class="study-content" v-if="+activeIndex === 1">
            <template v-if="Array.isArray(newsHistorys) && newsHistorys.length">
              <a
                v-for="(newsItem, index) in newsHistorys"
                :key="index"
                class="study-item flex-wrap flex-center-wrap flex-justify-between no-un-line"
                :href="parseFullPath(newsItem.url)"
                target="_blank"
              >
                <span class="study-left">
                  <span class="item-title text-ess-2">
                    {{ newsItem.title }}
                  </span>
                </span>
                <span class="study-right" v-if="newsItem.cover_url">
                  <img :src="parseResourceUrl(newsItem.cover_url)" alt="" />
                </span>
              </a>
            </template>
            <div v-else class="no-history-tip">暂无资讯浏览记录</div>
          </div>
          <div class="study-content" v-if="+activeIndex === 2">
            <template v-if="Array.isArray(lastStudys) && lastStudys.length">
              <a
                v-for="(studyItem, index) in lastStudys"
                :key="index"
                class="study-item flex-wrap flex-center-wrap flex-justify-between"
                :href="parseFullPath(studyItem.url)"
                target="_blank"
              >
                <span class="study-left">
                  <span class="item-title text-ess-2">
                    {{ studyItem.course_name }}
                  </span>
                </span>
                <span class="study-right" v-if="studyItem.cover_url">
                  <img :src="parseResourceUrl(studyItem.cover_url)" alt="" />
                </span>
              </a>
            </template>
            <div v-else class="no-history-tip">暂无课程浏览记录</div>
          </div>
        </div>
        <!-- 我的弹窗 -->
        <div v-if="isShowCourse" class="my-course-dialog">
          <div
            class="my-course-top flex-wrap flex-justify-between flex-center-wrap"
          >
            <div
              style="cursor: pointer"
              class="flex-wrap flex-center-wrap"
              @click="goTo('/personal/index.html', { target: '_blank' })"
            >
              <img
                class="my-header"
                :src="parseResourceUrl(userData.headimgurl)"
                alt="用户头像"
                title="用户头像"
              />
              <div>
                <div class="my-nickname text-ess-1">
                  {{ userData.nickname }}
                </div>
                <div class="my-slogin">欢迎来到之了课堂</div>
              </div>
            </div>
            <div class="logout-btn" @click="loginOut">退出</div>
          </div>

          <div
            class="my-course-bottom flex-wrap flex-justify-around flex-multi-row"
          >
            <a
              :target="
                ['投诉建议'].includes(menuItem.title) ? '_self' : '_blank'
              "
              :href="parseFullPath(menuItem.href || 'javascript:;')"
              class="fun-item flex-column-wrap flex-center-wrap"
              v-for="(menuItem, index) in myMenus"
              :key="index"
              @click="handleZla(menuItem.title, menuItem.title)"
              @mouseenter="menuItem.img = menuItem.hoverImg || menuItem.img"
              @mouseleave="menuItem.img = menuItem.defaultImg || menuItem.img"
            >
              <!-- <transition> -->
              <img class="fun-img" :src="menuItem.img" alt="" />
              <!-- </transition> -->
              <span class="fun-title">{{ menuItem.title }}</span>
            </a>
          </div>
        </div>
      </nav>
    </div>
    <!-- 新增搜索交互弹窗 -->
    <transition name="fade">
      <zl-search
        :fromDaYi="true"
        :historySearchs="hotSearch"
        :isLogin="isLogin"
        @inputSearch="inputSearch"
        @closeSearchDialog="closeSearchDialog"
        @deleteHistorys="deleteHistorys"
        v-if="isShowSearchBox"
        class="search-box-dialog"
      ></zl-search>
    </transition>
  </header>
</template>

<script>
import { clearKeywordsHistory } from '@/api/answer_question'
import slideNav from '../slideNav.vue'
import zlSearch from '@/components/searchDialog.vue'
export default {
  components: {
    'slide-nav': slideNav,
    'zl-search': zlSearch
  },
  data() {
    return {
      zlaBtn: {
        key_name: '',
        key_content: ''
      },
      // 我的菜单数据
      myMenus: [
        {
          img:
            '//image.zlketang.com/public/news/images/new_official/home/my-course-icon.png',
          title: '我的课程',
          href: '/personal/index.html?name=1'
        },
        {
          img:
            '//image.zlketang.com/public/news/images/new_official/home/my-test-icon.png',
          title: '我的题库',
          href: '/personal/index.html?name=2'
        },
        {
          img:
            '//image.zlketang.com/public/news/images/new_official/home/my-shop-icon.png',
          title: '商城中心',
          href: '/courses/'
        },
        {
          img:
            '//image.zlketang.com/public/news/images/new_official/home/answer-icon.png',
          defaultImg:
            '//image.zlketang.com/public/news/images/new_official/home/answer-icon.png',
          title: '答疑中心',
          href: '/dayi/'
        },
        {
          img:
            '//image.zlketang.com/public/news/images/new_official/home/test-guide-icon.png',
          title: '考试指南',
          href: '/cjkj/guide/'
        },
        {
          img:
            '//image.zlketang.com/public/news/images/new_official/home/suggestion-icon.png',
          title: '投诉建议'
        }
      ],
      newsHistorys: [],
      // 学习记录弹窗内容类型 1：课程：2：文章
      showStudyType: 1,
      activeIndex: 1,
      historyType: [
        {
          type: 1,
          label: '资讯'
        },
        {
          type: 2,
          label: '课程'
        }
      ],
      // 是否显示学习记录
      isShowStudy: false,
      // 是否显示我的课程
      isShowCourse: false,
      // 设置顶部导航栏样式类型1：默认;2:自定义；
      headStyleType: 1,
      //头部tab列表
      headerTabsNav: [
        {
          id: 1,
          name: '最新问答'
        },
        {
          id: 2,
          name: '精华答疑'
        },
        {
          id: 3,
          name: '我的提问'
        }
      ],
      //是否首次打开弹窗
      isFirstOpenBox: true,
      //是否显示搜索框
      isShowSearchBox: false,
      //搜索输入框内容
      searchText: '',
      //输入框是否聚焦
      isFocus: false
    }
  },
  computed: {
    userData() {
      return this.$store.state.user.userData
    },
    profession_name() {
      return this.$route.meta.profession_name
    },
    isLogin() {
      return this.$store.state.user.isLogin
    },
    currentNavTab() {
      return this.$store.state.answerQuestion.navTab
    },
    isClickMyQuesTab() {
      return this.$store.state.answerQuestion.isClickMyQuesTab
    },
    hotSearch() {
      return this.$store.state.answerQuestion.hotSearch
    },
    unReadCount() {
      return this.$store.state.answerQuestion.unreadCount
    }
  },
  watch: {
    // 之了埋点
    zlaBtn: {
      handler() {
        this.sendZlaClick()
      },
      deep: true
    }
  },
  methods: {
    // 之了数据点击
    sendZlaClick() {
      this.keyClick({
        ...this.zlaBtn
      })
    },
    // 监听页面点击事件,隐藏学习记录、我的弹窗
    handleBodyClick() {
      window.addEventListener('click', () => {
        this.isShowStudy = false
        this.isShowCourse = false
        this.isShowSearcHistorys = false
      })
    },
    // a标签点击事件埋点
    handleZla(name, content) {
      this.zlaBtn = {
        key_name: name,
        key_content: name
      }
      if (content === '投诉建议') {
        this.$bus.$emit('showTsDialog')
      }
    },
    // 切换记录类型
    handleHistory() {},
    // 退出登录
    loginOut() {
      this.$confirm('是否退出登录?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true,
        customClass: 'custom-confirm-box'
      })
        .then(async () => {
          await this.$store.dispatch('user/loginOut')
          this.$message({ type: 'success', message: '退出成功' })
          location.reload()
        })
        .catch(() => {})
    },
    aGoToLogin() {
      sessionStorage.setItem('lastUrl', location.href)
      this.goTo('/login.html')
    },
    // 展示学习记录
    showStudy() {
      this.zlaBtn = {
        key_name: '学习记录',
        key_content: '学习记录'
      }
      // 跳转登录页
      if (location.href.includes('login.html')) return
      this.isShowCourse = false
      if (!this.isLogin) {
        sessionStorage.setItem('lastUrl', location.href)
        this.goTo('/login.html')
      } else {
        this.isShowStudy = !this.isShowStudy
      }
    },

    //选择navTab
    chooseNavTab(index) {
      this.isShowSearchBox = false
      let { name } = this.headerTabsNav[index]
      if (name) {
        this.zlaBtn = {
          key_name: name,
          key_content: name
        }
      }

      if (index === 2 && !this.isLogin) {
        storage.set('answerNav', index + 1)
        this.$store.commit('answerQuestion/setNavTab', {
          currentNavTab: index + 1
        })
        sessionStorage.setItem('lastUrl', location.href)
        this.goTo('/login', {
          replace: true
        })
        return
      }

      this.$emit('change', index)
      if (this.currentNavTab < 4) {
        this.$store.commit('answerQuestion/setNavTab', {
          currentNavTab: index + 1
        })
      } else {
        storage.set('answerNav', index + 1)
        this.goTo('/dayi/', {
          query: {},
          target: '_blank',
          watch: true
        })
      }
    },
    //显示搜索框
    showSearchBox() {
      //仅在首次搜索的时候调用接口，用户登陆
      if (this.isFirstOpenBox && this.isLogin && this.hotSearch.length === 0) {
        this.isFirstOpenBox = false
        this.$store.dispatch('answerQuestion/getHotSearch')
      }
      this.searchText = ''
      this.isShowSearchBox = true
    },
    //搜索问题
    searchQuestion() {
      if (!this.searchText) return this.$message.warning('请输入问题进行搜索')
      this.zlaBtn = {
        key_name: '搜一搜',
        key_content: this.searchText
      }
      if (location.href.includes('ask') || location.href.includes('dayi')) {
        storage.set('searchAnswerText', this.searchText)
        this.goTo('/dayi/', {
          query: { from: 'ask' },
          target: '_blank',
          watch: true
        })
        return
      }
      this.$store.commit('answerQuestion/setKeyword', this.searchText)
      this.$store.dispatch('answerQuestion/getSearchQuestionResult', {
        page: 1,
        limit: 10,
        keywords: this.searchText
      })
      this.isShowSearchBox = false
    },
    //输入框聚焦
    inputFocus() {
      this.isFocus = true
    },
    inputBlur() {
      this.isFocus = false
    },
    //选择搜索
    chooseSearch(item) {
      this.searchText = item
      this.searchQuestion()
    },
    inputSearch(val) {
      this.searchText = val
      this.isShowSearchBox = false
      this.searchQuestion()
    },
    closeSearchDialog() {
      this.isShowSearchBox = false
    },
    deleteHistorys() {
      clearKeywordsHistory()
        .then(res => {
          this.$store.dispatch('answerQuestion/getHotSearch')
        })
        .catch(() => {})
    }
  },
  mounted() {
    let query = this.getQuery(location.href)
    if (query.from === 'new_all') {
      this.$store.commit('answerQuestion/setNavTab', { currentNavTab: 1 })
      this.$emit('changeProfession')
    }
    this.newsHistorys = storage.get('user_news_historys')
      ? JSON.parse(storage.get('user_news_historys'))
      : []
    this.handleBodyClick()
    window.addEventListener(
      'scroll',
      () => {
        this.closeSearchDialog()
      },
      true
    )
    let alink = document.getElementsByTagName('a')
    for (let i = 0; i < alink.length; i++) {
      alink[i].addEventListener('click', () => {
        this.isShowSearchBox = false
      })
    }
  }
}
</script>

<style scoped>
.answer-header {
  position: fixed;
  z-index: 1111;
  width: 100%;
  height: 74px;
  background-color: #fff;
  -webkit-transition: all 0.3s;
  -o-transition: all 0.3s;
  transition: all 0.3s;
}

.header-box-inner {
  position: relative;
  width: 1200px;
  height: 100%;
  margin: 0 auto;
}

.web-logo {
  width: 116px;
  height: 34px;
}

.header-interval-sign {
  margin: 0 10px 5px 10px;
  color: #3480ff;
}
.answer-logo-box {
  width: 96px;
  height: 34px;
}
.answer-logo {
  width: 96px;
  height: 20px;
}
.header-center {
  height: 100%;
  margin-left: 152px;
}
.header-tab-item {
  position: relative;
  line-height: 22px;
  margin-right: 40px;
  font-size: 16px;
  font-weight: 500;
  color: #999999;
  cursor: pointer;
}

.header-tab-item-count {
  position: absolute;
  left: 66px;
  top: -10px;
  line-height: 18px;
  padding: 0 4px;
  background-color: #ff5338;
  font-size: 12px;
  color: #fff;
  border-radius: 8px;
}
.header-tab-item-active {
  color: #383838;
}
.header-tab-item-active::after {
  content: '';
  position: absolute;
  bottom: -10px;
  left: calc(50% - 15px);
  width: 30px;
  height: 3px;
  background-color: #3480ff;
  border-radius: 2px;
}
.header-tab-item:last-child {
  margin-right: 0;
}

.header-right {
  position: absolute;
  height: 100%;
  right: 0;
  top: 0;
}

.header-right .head-study-btn {
  /* css-ignore */
  color: #666666;
  text-decoration: none;
}
.header-right .head-study-btn-login {
  /* css-ignore */
  color: #666666;
}
.header-right .head-study-btn:hover,
.header-right .head-study-btn-login:hover {
  /* css-ignore */
  color: #383838;
}
.my-header {
  margin-left: 10px;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  cursor: pointer;
}

.header-right .head-study-btn-login {
  /* css-ignore */
  color: #666666;
}
.header-right .head-study-btn:hover,
.header-right .head-study-btn-login:hover {
  /* css-ignore */
  color: #383838;
}
.get-course-btn {
  text-decoration: none;
  text-align: center;
  width: 78px;
  line-height: 30px;
  border-radius: 16px;
  cursor: pointer;
}

.get-course-btn {
  /* css-ignore */
  background: #ffffff;
  color: #666666;
  border-radius: 16px;
  border: 1px solid #666666;
}
.get-course-btn:hover {
  color: #383838;
  border: 1px solid #383838;
}
.vertical-split-line {
  width: 1px;
  height: 20px;
  margin: 0 15px;
  background: #999999;
}
/* .m-l-16 {
  margin-left: 16px;
} */
/* 学习记录弹窗 */
.study-dialog {
  position: absolute;
  top: 60px;
  right: 0;
  padding: 20px 0 8px 0;
  background: #ffffff;
  box-shadow: 0px 2px 10px 0px rgba(205, 205, 205, 0.5);
  border-radius: 12px;
}

.study-content {
  padding: 0 20px;
  max-height: 330px;
  overflow: auto;
  margin-top: 20px;
}
.study-item {
  cursor: pointer;
  margin-top: 20px;
  width: 272px;
  /* height: 63px; */
}
.study-item:first-of-type {
  margin-top: 0;
}
.item-title {
  display: block;
  /* max-width: 136px; */
  font-size: 14px;
  font-weight: 400;
  color: #383838;
  line-height: 18px;
}

.study-right {
  display: block;
}
.study-right img {
  margin-left: 48px;
  width: 88px;
  height: 58px;
  border-radius: 8px;
}

/* 学习记录弹窗 */
.study-dialog {
  position: absolute;
  top: 60px;
  right: 0;
  padding: 20px 0 8px 0;
  background: #ffffff;
  box-shadow: 0px 2px 10px 0px rgba(205, 205, 205, 0.5);
  border-radius: 12px;
}

.study-content {
  padding: 0 20px;
  max-height: 330px;
  overflow: auto;
  margin-top: 20px;
}
.study-item {
  cursor: pointer;
  margin-top: 20px;
  width: 272px;
  /* height: 63px; */
}
.study-item:first-of-type {
  margin-top: 0;
}
.item-title {
  display: block;
  /* max-width: 136px; */
  font-size: 14px;
  font-weight: 400;
  color: #383838;
  line-height: 18px;
}

.study-right {
  display: block;
}
.study-right img {
  margin-left: 48px;
  width: 88px;
  height: 58px;
  border-radius: 8px;
}
.study-btn {
  text-decoration: none;
  display: block;
  text-align: center;
  cursor: pointer;
  margin-top: 30px;
  background: #f4f6ff;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 400;
  color: #999999;
  line-height: 36px;
}
.header-right .head-study-btn {
  /* color: inherit; */
  text-decoration: none;
  font-size: 14px;
  font-weight: 400;
  line-height: 20px;
}
/* 头像弹窗 */
.my-course-dialog {
  position: absolute;
  top: 60px;
  right: 0;
  border-radius: 12px;
  width: 288px;
  background: #ffffff;
  box-shadow: 0px 2px 10px 0px rgba(205, 205, 205, 0.5);
}
.my-course-top {
  padding: 16px 20px;
  background: url('//image.zlketang.com/public/news/images/new_official/home/my-course-top-bg.png');
  background-size: contain;
  background-repeat: no-repeat;
}
.my-nickname {
  margin-left: 10px;
  font-size: 18px;
  font-weight: bold;
  color: #383838;
  line-height: 25px;
  max-width: 120px;
}
.my-slogin {
  margin-top: 6px;
  margin-left: 10px;
  font-size: 12px;
  font-weight: 400;
  color: #999999;
  line-height: 17px;
}
.logout-btn {
  cursor: pointer;
  font-size: 14px;
  font-weight: 400;
  color: #666666;
  line-height: 20px;
}
.my-course-bottom {
  padding-bottom: 15px;
}
.fun-item {
  margin: 20px 20px 0;
  text-decoration: none;
  color: #666666;
}
.fun-img {
  width: 40px;
  height: 40px;
  border-radius: 50%;
}
.fun-title {
  display: block;
  margin-top: 6px;
  font-size: 14px;
  font-weight: 400;
  color: #666666;
  line-height: 20px;
}
.study-dialog /deep/ .study-slide-nav {
  width: 136px;
  height: 40px;
  line-height: 40px !important;
  border-radius: 8px;
  font-size: 16px !important;
  font-weight: 400;
  text-align: center;
  padding: 0 !important;
}
.no-history-tip {
  padding: 10px 0 22px;
  color: #999999;
  text-align: center;
  line-height: 22px;
}
.study-left {
  display: block;
  height: 36px;
}
.no-un-line {
  text-decoration: none;
}
.search-box-new {
  position: relative;
  margin-right: 15px;
}
.search-input-new {
  width: 36px;
  height: 36px;
  border: none;
  outline: 0;
  padding: 0;
  border-radius: 18px;
  background: #f7f7f7;
  transition: width 0.3s ease;
}
.search-icon {
  position: absolute;
  top: 0;
  right: 0px;
  width: 36px;
  height: 36px;
  cursor: pointer;
  transition: all 0.3s ease;
  color: #999999;
}
.search-icon:hover {
  color: #666666;
}
.search-box-dialog {
  position: fixed;
  width: 100%;
  background: rgba(0, 0, 0, 0.4);
  height: 100vh;
  z-index: 200;
}
.fade-enter-active {
  /* css-ignore */
  transition: opacity 0.4s ease-in-out;
}
.fade-leave-active {
  /* css-ignore */
  transition: opacity 0.4s ease-in-out;
}
.fade-enter {
  /* css-ignore */
  opacity: 0;
}
.fade-leave-to {
  /* css-ignore */
  opacity: 0;
}
</style>
